<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Strings in Tcl</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Tcl, learn Tcl, strings, programming, tutorials">
<meta name="description" content="In this chapter of the Tcl tutorial, we will
work with strings.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Strings in Tcl</h1>

<p>
In this part of the Tcl tutorial, we will work with string 
data in more detail.  
String is an important data type in computer languages. 
</p>

<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* LargeSquare */
google_ad_slot = "5070696322";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

<p>
A string is a sequence of characters. String in Tcl, unlike in other languages,
may not be enclosed within double quotes. They are necessary only if
we have a space between words. Tcl is a string based language. 
It provides a rich set of commands for manipulating strings.
</p>


<h2>First example</h2>

<p>
A simple example showing some strings follows. 
</p>


<pre class="code">
#!/usr/bin/tclsh

puts Tcl
puts Java
puts Falcon

puts "Tcl language"
puts {Tcl language}
</pre>

<p>
The script prints some string values to the console. 
</p>

<pre class="explanation">
puts Tcl
puts Java
puts Falcon
</pre>

<p>
Strings in Tcl may not be enclosed within quotes. 
</p>

<pre class="explanation">
puts "Tcl language"
puts {Tcl language}
</pre>

<p>
Strings in Tcl can be grouped with double quotes or 
curly brackets. 
</p>

<pre>
$ ./simple.tcl 
Tcl
Java
Falcon
Tcl language
Tcl language
</pre>

<p>
Output.
</p>


<h2>Using quotes</h2>

<p>
What if we wanted to display quotes, for example in a direct speech?
In such a case, inner quotes must be escaped.
</p>

<pre class="code">
$ cat directspeech.tcl
#!/usr/bin/tclsh

puts "There are many stars"
puts "He said, \"Which one is your favourite?\""
</pre>

<p>
We use the (\) character to escape additional quotes.
</p>

<pre>
$ ./directspeech.tcl
There are many stars
He said, "Which one is your favourite?"
</pre>

<p>
Output. 
</p>

<h2>Multiline strings</h2>

<p>
It is very easy to create a multiline string in Tcl. 
I many other languages creating multiline strings is much
less convenient. 
</p>

<pre class="code">
#!/usr/bin/tclsh

set lyrics "I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good"

puts $lyrics
</pre>

<p>
We simple continue on the next line. This is useful if we wanted to 
display verses. 
</p>

<pre>
$ ./multiline.tcl
I cheated myself
like I knew I would
I told ya, I was trouble
you know that I'm no good
</pre>


<h2>Comparing strings</h2>

<p>
Basic comparison of strings can be done with the <code>string compare</code> command. 
<!--Strings are not compared with the == operator in Tcl, which is common in many popular languages.-->
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [string compare 12 12]
puts [string compare Eagle Eagle]
puts [string compare Eagle eagle]
puts [string compare -nocase Eagle eagle]
</pre>

<p>
The <code>string compare</code> command compares strings character by character.
If it finds that the first characters of both strings are equal, it continues with
the second character. Until the end.
It returns 0, if the strings are equal. -1 if a character in the first string is
located in the ascii table before the character of the second string. 1 if the
character of the first string is located after the character of the second string.
</p>

<pre class="explanation">
puts [string compare 12 12]
</pre>

<p>
In this context, 12 is a string.
</p>

<pre class="explanation">
puts [string compare Eagle Eagle]
</pre>

<p>
Two strings are equal, 0 is printed to the console. 
</p>

<pre class="explanation">
puts [string compare Eagle eagle]
</pre>

<p>
E stands before e, -1 is returned. 
</p>

<pre class="explanation">
puts [string compare -nocase Eagle eagle]
</pre>

<p>
With the -nocase option, we ignore the case. 
The two strings are equal. 
</p>

<pre>
$ ./compare.tcl
0
0
-1
0
</pre>

<p>
Output of the program. 
</p>

<hr class="btm">

<p>
The <code>string equal</code> also can be used to compare strings. 
The command returns 1, if the strings are equal, and 0 if they are not.
</p>

<pre class="code">
#!/usr/bin/tclsh

set str1 Tcl
set str2 "Tcl language"

puts [string compare $str1 $str2]
puts [string compare -length 3 $str1 $str2]

puts [string equal $str1 $str2]
puts [string equal -length 3 $str1 $str2]
</pre>

<p>
The script shows both commands comparing strings.
</p>

<pre class="explanation">
puts [string compare $str1 $str2]
</pre>

<p>
The line prints -1. The characters on the first three positions
 are equal. On the fourth position the <code>string compare</code> command
compares white space with the l character. The space is located
before the l character in the ascii table. Strings are not equal.
</p>

<pre class="explanation">
puts [string compare -length 3 $str1 $str2]
</pre>

<p>
In this case, we limit the comparing to first three characters.
They are same in both strings, so the command returns 0. 
</p>

<pre class="explanation">
puts [string equal $str1 $str2]
</pre>

<p>
The two strings are not identical, so the <code>string equal</code>
command returns 0, for false. 
</p>

<pre class="explanation">
puts [string equal -length 3 $str1 $str2]
</pre>

<p>
Limiting strings to the first three characters, the command returns 1.
Which means, they are identical up to the first three characters.
</p>

<h2>Unicode</h2>

<p>
We can use unicode strings in our Tcl scripts. 
</p>


<pre class="code">
#!/usr/bin/tclsh

puts "La femme vit par le sentiment, là où l'homme vit par l'action"
puts "Анна Каренина"
</pre>

<p>
We print two messages to the terminal. The first is in French, the
second in Russian. 
</p>

<pre>
$ ./unicode.tcl
La femme vit par le sentiment, là où l'homme vit par l'action
Анна Каренина
</pre>

<p>
Output.
</p>



<h2>String commands</h2>

<p>
Tcl has useful built-in commands that can be used for working with strings. 
</p>

<pre class="code">
#!/usr/bin/tclsh

set str Eagle

puts [string length $str]

puts [string index $str 0]
puts [string index $str end]

puts [string range $str 1 3]
</pre>

<p>
We define a string variable and work with some string commands. 
</p>

<pre class="explanation">
puts [string length $str]
</pre>

<p>
The <code>string length</code> returns the number of characters in
the string. 
</p>

<pre class="explanation">
puts [string index $str 0]
puts [string index $str end]
</pre>

<p>
The <code>string index</code> command returns the character at
a specific position. 
</p>

<pre class="explanation">
puts [string range $str 1 3]
</pre>

<p>
The <code>string range</code> returns a range of characters, selected
by the first and last index. 
</p>

<pre>
$ ./strings1.tcl
5
E
e
agl
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
We have a <code>split</code> command to split strings at a specific character.
The command returns a list of words. These words can be combined together
into a string with the <code>join</code> command.
</p>

<pre class="code">
#!/usr/bin/tclsh

set langs "Tcl,Java,C,C#,Ruby,Falcon"

puts [split $langs ,]
puts [join [split $langs ","] ":"]
</pre>

<p>
In our program, we will split and join strings.
</p>

<pre class="explanation">
set langs "Tcl,Java,C,C#,Ruby,Falcon"
</pre>

<p>
This is a string we are going to split. There are several words
separated by a comma character. The comma character is the character,
by which we will split the string. 
</p>

<pre class="explanation">
puts [split $langs ,]
</pre>

<p>
The line prints all words that we have split from the string.
</p>

<pre class="explanation">
puts [join [split $langs ","] ":"]
</pre>

<p>
The <code>split</code> command returns a list of words from the
string. These words are then joined. The words will be now separated
by the colon. 
</p>

<pre>
$ ./splitjoin.tcl 
Tcl Java C C# Ruby Falcon
Tcl:Java:C:C#:Ruby:Falcon
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
Next we will have another example with a few
string commands. 
</p>

<pre class="code">
#!/usr/bin/tclsh

set str "ZetCode" 

puts [string toupper $str]
puts [string tolower $str]
puts [string totitle $str]
puts [string reverse $str]
</pre>

<p>
We introduce four string commands. The 
commands do not change the original string.
They return a new, modified string. 
</p>

<pre class="explanation">
puts [string toupper $str]
</pre>

<p>
We convert the characters to uppercase. 
</p>

<pre class="explanation">
puts [string tolower $str]
</pre>

<p>
We convert letters of the string to lowercase.
</p>

<pre class="explanation">
puts [string totitle $str]
</pre>

<p>
The <code>string totitle</code> returns a string with
the first character in uppercase; other characters are in lowercase.
</p>

<pre class="explanation">
puts [string reverse $str]
</pre>

<p>
We reverse the characters of the string with the
<code>string reverse</code> command. 
</p>


<pre>
$ ./strings2.tcl 
ZETCODE
zetcode
Zetcode
edoCteZ
</pre>

<p>
Running the program. 
</p>


<h2>Formatting strings</h2>

<p>
The very basic formatting of strings is done within the
quotes. 
</p>

<pre class="code">
#!/usr/bin/tclsh

set oranges 2
set apples 4
set bananas 3

puts "There are $oranges oranges, $apples apples and\
$bananas bananas. "
</pre>

<p>
Tcl evaluates variables in double quotes. 
</p>

<pre class="explanation">
puts "There are $oranges oranges, $apples apples and\
$bananas bananas. "
</pre>

<p>
In this code line, we combine variables and strings
in one sentence. 
</p>

<pre>
$ ./fruit.tcl
There are 2 oranges, 4 apples and 3 bananas.
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
More advanced formatting can be done with the <code>format</code> command.
It has the following synopsis.
</p>

<pre>
format formatString ?arg arg ...?
</pre>

<p>
The formatString is used to control, how the arguments are going to be
displayed. The command can take multiple arguments. 
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [format %s "Inception movie"]
puts [format "%d %s" 23 songs]
</pre>

<p>
This is basic script showing the usage of the <code>format</code> command.
</p>

<pre class="explanation">
puts [format %s "Inception movie"]
</pre>

<p>
This line simply prints a string to the console. 
</p>

<pre class="explanation">
puts [format "%d %s" 23 songs]
</pre>

<p>
Here we print two arguments. Each argument has a format specifier, 
which begins with the % character. 
</p>

<pre>
$ ./basicformat.tcl
Inception movie
23 songs
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
Now we show some basic conversion specifiers
for the <code>format</code> command. %s, %f, %d, %e are conversion
types. They control how the value is displayed. Conversion type
is the only mandatory part of the conversion specifier. 
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [format "%s" "Tcl language"]
puts [format "%f" 212.432]
puts [format "%d" 20000]
puts [format "%e" 212.342]
</pre>

<p>
We will print four messages to the terminal. 
</p>

<pre class="explanation">
puts [format "%s" "Tcl language"]
</pre>

<p>
The %s is a conversion type for the string. 
</p>

<pre class="explanation">
puts [format "%f" 212.432]
</pre>

<p>
%f is used to display decimal numbers.
</p>

<pre class="explanation">
puts [format "%d" 20000]
</pre>

<p>
To print an integer value, we use the %d conversion type. 
</p>

<pre class="explanation">
puts [format "%e" 212.342]
</pre>

<p>
The %e is used to show number in a scientific format.
</p>

<pre>
$ ./format.tcl
Tcl language
212.432000
20000
2.123420e+02
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
In the next example, we will be formatting numbers in three different
number formats. 
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [format "%-10s %-14s %s" Decimal Hexadecimal Octal]

puts [format "%-10d %-14x %o" 5000 5000 5000]
puts [format "%-10d %-14x %o" 344 344 344]
puts [format "%-10d %-14x %o" 55 55 55]
puts [format "%-10d %-14x %o" 9 9 9]
puts [format "%-10d %-14x %o" 15666 15666 15666]
</pre>

<p>
We print numbers in a decimal, hexadecimal and octal
format. We also align the numbers in three columns.
</p>

<pre class="explanation">
puts [format "%-10d %-14x %o" 5000 5000 5000]
</pre>

<p>
The %-10d applies for the first number, %-14x for the second
and %o for the third. We will describe the first one.
The format specifier begins with the %
character. The minus sign (-) tells, that if the value will
be shorter than the field width, it is left justified. 
The rest of the field is padded with white space. 
The number (10) specifies the field width. Finally the d
character tells that the number is displayed in decimal format.
The x stands for hexadecimal and o for octal. 
</p>

<pre>
$ ./numbers.tcl
Decimal    Hexadecimal    Octal
5000       1388           11610
344        158            530
55         37             67
9          9              11
15666      3d32           36462
</pre>

<p>
Running the example. 
</p>


<hr class="btm">

<p>
Finally, we will format date and time data. We use
the <code>clock format</code> command. 
</p>

<pre class="code">
#!/usr/bin/tclsh

set secs [clock seconds]

puts "Short date: [clock format $secs -format %D]"
puts "Long date: [clock format $secs -format "%A, %B %d, %Y"]"
puts "Short time: [clock format $secs -format %R]"
puts "Long time: [clock format $secs -format %r]"
puts "Month: [clock format $secs -format %B]"
puts "Year: [clock format $secs -format %Y]"
</pre>

<p>
The preceding example demonstrates some common date and
time formats. 
</p>

<pre class="explanation">
set secs [clock seconds]
</pre>

<p>
We get the current timestamp in seconds. This value is later
passed to the <code>clock format</code> command, to get dates and
times readable for humans. 
</p>

<pre class="explanation">
puts "Short date: [clock format $secs -format %D]"
</pre>

<p>
The format of the date is controlled with the <code>-format</code> option.
There are several specifiers. The %D returns a date in month/day/year format.
</p>

<pre>
$ ./clockformat.tcl
Short date: 04/11/2011
Long date: Monday, April 11, 2011
Short time: 11:30
Long time: 11:30:30 am
Month: April
Year: 2011
</pre>

<p>
Output.
</p>

<p>
This part of the Tcl tutorial covered strings. 
</p>

<br>
<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified April 11, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

